package com.cloudm.technician.ui.modules.cloudm_box.change_box

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.View
import android.view.ViewGroup
import com.cloudm.technician.R
import com.cloudm.technician.data.model.DeviceInfo
import com.cloudm.technician.extensions.openActivity
import com.cloudm.technician.extensions.toast
import com.cloudm.technician.ui.base.BaseAdapter
import com.cloudm.technician.ui.base.BaseListFragment
import com.cloudm.technician.ui.modules.cloudm_box.cloudm_device.CloudmDeviceActivity
import com.cloudm.technician.ui.modules.cloudm_box.machine_list.MachineListAdapter
import com.cloudm.technician.ui.modules.cloudm_box.machine_list.MachineListDialogFragment
import com.cloudm.technician.ui.modules.scan_qr_code.ScanQrCodeActivity
import com.cloudm.technician.ui.widget.OnceClickListener
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem
import kotlinx.android.synthetic.main.common_empty_view.*
import kotlinx.android.synthetic.main.fragment_machine_list.*

/**
 * 作者: wesley
 * 时间: 2017/12/18
 * 描述: ui
 */
class ChangeBoxFragment : BaseListFragment<ChangeBoxPresenter, DeviceInfo>(),
        ChangeBoxContract.View, MachineListAdapter.OnItemClickListener,
        MachineListDialogFragment.OnDialogItemClickListener {

    private lateinit var adapter: MachineListAdapter

    override val enabledRefresh: Boolean
        get() = true

    override val resource: Int
        get() = R.layout.fragment_machine_list

    companion object {
        private const val TAG = "ChangeBoxFragment"
        private const val REQUEST_CODE_PERMISSIONS = 1
        fun newInstance() = ChangeBoxFragment()
    }

    override fun onItemClick(t: DeviceInfo) {

    }

    override fun onMachineStatusClick(info: DeviceInfo) {
        openActivityByStatus(info)
    }

    override fun initInject() {
        DaggerChangeBoxComponent.builder().appComponent(appComponent).changeBoxPresenterModule(
                ChangeBoxPresenterModule(this)).build().inject(this)
    }

    override fun handleBundle(bundle: Bundle) {

    }

    override fun createAdapter(): BaseAdapter<DeviceInfo> {
        adapter = MachineListAdapter()
        adapter.listener = this
        return adapter
    }

    override fun loadData() {
        presenter?.getChangeBoxListInfo(startPage, PAGE_SIZE, 0)
    }

    override fun onResume() {
        super.onResume()
        refresh()
    }

    override fun initSwipeMenu() {
        recyclerView.setSwipeMenuCreator { _, swipeRightMenu, _ ->
            val menuItem = SwipeMenuItem(mContext).apply {
                setBackgroundColor(ContextCompat.getColor(mContext, R.color.color_ff0000))
                setText(R.string.delete)
                setTextColor(ContextCompat.getColor(mContext, R.color.common_color_ffffff))
                textSize = 16
                height = ViewGroup.LayoutParams.MATCH_PARENT
                width = mContext.resources.getDimensionPixelSize(R.dimen.item_machine_menu_height)
            }
            swipeRightMenu?.addMenuItem(menuItem)
        }

        recyclerView.setSwipeMenuItemClickListener { menuBridge ->
            menuBridge?.closeMenu()
            val adapterPosition = menuBridge?.adapterPosition ?: -1
            if (adapter.list.size > adapterPosition && adapterPosition >= 0) {
                showDeleteDialog(adapter.list[adapterPosition])
            } else {
                mContext.toast(mContext.resources.getString(R.string.unknow_error))
            }
        }
    }

    override fun deleteSuccess() {
        mContext.toast(mContext.resources.getString(R.string.device_delete_success))
        refresh()
    }

    override fun deleteFailure(errorMsg: String) {
        mContext.toast(errorMsg)
    }

    private fun showDeleteDialog(info: DeviceInfo) {
        val fragment = MachineListDialogFragment.newInstance(info)
        fragment.listener = this
        fragment.show(childFragmentManager, TAG)
    }

    override fun onDeleteClick(info: DeviceInfo) {
        presenter?.deleteDevice(info.recordId)
    }

    override fun initListener() {
        super.initListener()
        btnAdd.setOnClickListener(object : OnceClickListener() {
            override fun onOnceClick(view: View) {
                requestPermission()
            }
        })
    }

    override fun showEmptyView() {
        super.showEmptyView()
        btnAdd.visibility = View.GONE

        emptyValue.text = mContext.resources.getString(R.string.change_box)
        emptyValue.setOnClickListener(object : OnceClickListener() {
            override fun onOnceClick(view: View) {
                requestPermission()
            }
        })
    }

    override fun showContentView() {
        super.showContentView()
        btnAdd.visibility = View.VISIBLE
    }


    override fun showSnEmpMsg() {
        mContext.toast(mContext.resources.getString(R.string.sn_code_cannot_empty))
    }

    override fun showSnFormatErrMsg() {
        mContext.toast(mContext.resources.getString(R.string.sn_format_error))
    }

    override fun openCloudmDeviceDetailActivity(sn: String) {
        val intent = Intent(mContext, CloudmDeviceActivity::class.java).apply {
            putExtras(Bundle().apply {
                putString("sn", sn)
            })
        }
        mContext.openActivity(intent, false)
    }

    private fun requestPermission() {
        requestPermissionsForScanQrCode()
    }

    override fun scanRrCodeGrantedSuccess() {
        super.scanRrCodeGrantedSuccess()
        val intent = Intent(mContext, ScanQrCodeActivity::class.java).apply {
            putExtras(Bundle().apply {
                putInt("flag", 2)
            })
        }
        startActivityForResult(intent, REQUEST_CODE_PERMISSIONS)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode != Activity.RESULT_OK) {
            return
        }
        when (requestCode) {
            REQUEST_CODE_PERMISSIONS -> {
                presenter?.dealWithScanResult(data?.extras?.getString("result"))
            }
        }
    }

}